<template>
  <!--自定义查询区域 -->
  <div class="jeecg-basic-table jeecg-basic-table-form-container">
    <a-form @keyup.enter.native="searchQuery" style="width: 100%">
      <a-row :gutter="8" type="flex">
        <a-col flex="355px">
          <a-form-item label="放款日期" :label-col="{ style: { width: '70px' } }" :wrapper-col="{ style: { width: '250px' } }">
            <a-date-picker
              v-model:value="queryParam.beginDate"
              :disabled-date="disabledStartDate"
              valueFormat="YYYY-MM-DD"
              placeholder=""
              style="width: 125px"
            /> ~
            <a-date-picker
              v-model:value="queryParam.endDate"
              :disabled-date="disabledEndDate"
              valueFormat="YYYY-MM-DD"
              placeholder=""
              style="width: 125px"
            />
          </a-form-item>
        </a-col>

        <a-col flex="180px">
          <a-form-item label="区域" :label-col="{ style: { width: '50px' } }" :wrapper-col="{ span: 18 }">
            <JDictSelectTag
              v-model:value="queryParam.region"
              dictCode="sys_depart@authDepart"
              placeholder="全部"
              :maxTagCount="0"
              :getPopupContainer="(node) => node.parentNode"
              :dropdownStyle="{ width: '150px', overflow: 'auto' }"
              :dropdownMatchSelectWidth="false"
              @change="getUserOptions"
            />
          </a-form-item>
        </a-col>

        <a-col flex="180px">
          <a-form-item label="签单员" :label-col="{ style: { width: '60px' } }" :wrapper-col="{ span: 18 }">
            <!--JDictSelectTag
              v-model:value="queryParam.soleId"
              mode="multiple"
              dictCode="sys_user,realname,id@authUser"
              placeholder="全部"
              :maxTagCount="0"
              :getPopupContainer="(node) => node.parentNode"
              :dropdownStyle="{ width: '150px', overflow: 'auto' }"
              :dropdownMatchSelectWidth="false"
            /-->
            <a-select v-model:value="queryParam.soleIds" mode="multiple" :maxTagCount="0" :allowClear="true">
              <template v-for="item in userOptions" :key="`${item.value}`">
                <a-select-option :value="item.value">{{ item.label }}</a-select-option>
              </template>
            </a-select>
          </a-form-item>
        </a-col>

        <a-col flex="300px">
          <a-form-item label="资方产品" :label-col="{ style: { width: '66px' } }">
            <Cascader 
              v-model:value="cascader.ids" 
              :options="cascader.options" 
              placeholder="请选择" 
              expandTrigger="hover"
              stringToNumber 
              @change="customerCascader" 
              :show-search="{ filter }" 
            />
          </a-form-item>
        </a-col>

        <a-col flex="150px">
          <div style="height: 30px; line-height: 30px; font-size: 11px; font-weight: 600; cursor: pointer;" 
            :style="{color : queryParam.model == '1' ? 'red' : '#333'}"
            v-show="summaryData.qyNotFonndCn > 0" 
            @click="qyNotFonndQuery"> 
            发现有异常数据 <span style="font-size: 16px; ">{{ summaryData.qyNotFonndCn }}</span> 笔 
          </div>
        </a-col> 

        <a-col flex="auto" style="float:right; width:150px; ">
          <span style="float: right;overflow: hidden;" class="table-page-search-submitButtons">
            <a-button type="primary" @click="searchQuery" preIcon="ant-design:search">查询</a-button>
          </span>
        </a-col>
      </a-row>
    </a-form>
  </div>
  <div>
    <!--引用表格 :rowClassName="rowClassName"-->
    <BasicTable @register="registerTable" :onRowClick="handleClick" :onRowDbClick="handleDblclick" :rowClassName="rowClassName" :indexColumnProps="indexColumnProps" :scroll="{ x: 2200 }">
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" color="success" preIcon="ant-design:plus-outlined" @click="handleAdd" > 新增</a-button>
        <a-button type="primary" preIcon="ant-design:edit-outlined" @click="handleEdit"> 编辑 </a-button>
        <a-button type="primary" color="error" preIcon="ant-design:clear-outlined" @click="handleDelete"> 删除 </a-button>
        <a-button type="primary" color="warning" preIcon="ant-design:export-outlined" @click="onExportXls"> 导出</a-button>
        <j-upload-button type="primary" color="success" preIcon="ant-design:import-outlined" @click="onImportXls">导入</j-upload-button>
        <a-button type="primary" color="error" preIcon="ant-design:font-colors-outlined" @click="handleDetail"> 明细 </a-button> 
        <div v-if="!!summaryData.amountTotal" style="height: 30px; line-height: 30px; min-width: 600px;">
          <span>融资总金额<label class="text-red-500">{{summaryData.amountTotal}}</label></span>
          <span>融资总台数<label class="text-red-500">{{summaryData.total}}</label></span>
          <span>GPS 总费用<label class="text-red-500">{{summaryData.gpsCost}}</label></span>
          <span>车商总返利<label class="text-green-500">{{summaryData.dealerRebate}}</label></span>
          <span>税金总支出<label class="text-green-500">{{summaryData.zfTaxAmount}}</label></span>
          <span>区域总提成<label class="text-green-500">{{summaryData.qyProfitAmount}}</label></span>
          <span>区域总毛利<label class="text-blue-500">{{summaryData.zfProfitGross}}</label></span>
          <span v-if="hasPermission('order:shareholder')">股东总毛利<label class="text-blue-500">{{summaryData.nbProfitGross}}</label></span>
        </div>
      </template>
    </BasicTable>

    <!-- 表单区域 -->
    <OrdersModal @register="registerModal" @success="handleSuccess"></OrdersModal>

    <!-- 表单区域 -->
    <OrdersDetail @register="registerDetail" @success="handleSuccess"></OrdersDetail>
  </div>
</template>

<script lang="ts" name="orders-list" setup>
import { ref, computed, unref, reactive, toRaw, onMounted, nextTick } from 'vue';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { Cascader } from 'ant-design-vue';
import { useModal } from '/@/components/Modal';
import { useListPage } from '/@/hooks/system/useListPage';
import { columns } from './Orders.data';
import { list, deleteOne, getImportUrl, getExportUrl } from './Orders.api';
import { customerSelect } from '/@/views/good/product/Product.api';
import { getUsersByDepartId } from '/@/api/common/api';

import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
import OrdersModal from './modules/OrdersModal.vue';
import OrdersDetail from './modules/OrdersDetail.vue';
import moment from 'dayjs'
import { usePermission } from '/@/hooks/web/usePermission';

const { hasPermission } = usePermission();

// 2、用户下接
const userOptions = ref<any>([]);

//初始化 -------------------------------------------------------------
//定义查询表单，查询条件
const queryParam = reactive<any>({
  regions: [],
  capitals: [],
  model: '0',
  beginDate : moment().subtract( 5, 'months').format('YYYY-MM-01'),
  endDate: moment().add( 0, 'months').endOf('month').format('YYYY-MM-DD')
});

const options = ref([]);

//限制查询日期，开始日期不能大于结束日期
function disabledStartDate(beginDate) {
  const endDate = queryParam.endDate;
  if (!beginDate || !endDate) {
    return false;
  }
  return beginDate.valueOf() > moment(endDate).valueOf()
}

function disabledEndDate(endDate) {
  const beginDate = queryParam.beginDate;
  if (!endDate || !beginDate) {
    return false;
  }
  return moment(beginDate).valueOf() > endDate.valueOf();
}
//初始化 -------------------------------------------------------------

//注册model
const [registerModal, { openModal }] = useModal();

//注册model
const [registerDetail, { openModal : openDetail }] = useModal();

/**
 * 序号列配置
 */
const indexColumnProps = {
  dataIndex: 'index',
  width: '15px',
};

//注册table数据
const { tableContext, onExportXls, onImportXls } = useListPage({
  tableProps: {
    api: list,
    columns: columns,
    showIndexColumn: true,    //行号
    clickToRowSelect: true,   //点击选择
    showActionColumn: false,
    useSearchForm: false,
    showSummary: false,
    showTableSetting: false,
    afterFetch: handleSummary,
    beforeFetch: (params) => {Object.assign(params, unref(queryParam))}, 
  },
  exportConfig: {
    name: '放款台账',
    url: getExportUrl,
  },
  importConfig: {
    url: getImportUrl,
  },
});

//注册table数据
const [registerTable, {reload, setProps, getRawDataSource, redoHeight}] = tableContext

function qyNotFonndQuery() {
  if (queryParam.model == '1') {
    queryParam.model = '0'
  } else {
    queryParam.model = '1'
  }
}

function searchQuery() {
  setProps({searchInfo:toRaw(queryParam)});
  reload()
}

const summaryData = ref<any>({});
function handleSummary() {
  const res = getRawDataSource()
  redoHeight();
  if (res && res.summary.length > 0) {
    summaryData.value = {
      ...res.summary[0],
      total: res.total
    }
  } else {
    summaryData.value = {
      amountTotal: '',
      gpsCost: '',
      dealerRebate: '',
      zfTaxAmount: '',
      qyPercentage: '',
      zfProfitGross: '',
      nbProfitGross: '',
      qyNotFonndCn: '',
      total: ''
    }
  }
}

/**
 * 新增事件
 */
function handleAdd() {
  openModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}

/**
 * 编辑事件
 */
function handleEdit(record: Recordable) {
  if (!selectRows.id) {
    return
  }
  Object.assign(record, selectRows)
  openModal(true, {
    record,
    isUpdate: true,
    showFooter: true,
  });
}

/**
 * 成功回调
 */
function handleSuccess() {
  reload();
}

//单击行
let selectRows = reactive<any>({id: ''});
function handleClick(record) {
  // if (selectRows.id == record.id) {
  //   selectRows.id = ''
  // } else {
    
  // }
  selectRows.id = record.id
}

//双击行
function handleDblclick(record) {
  if (!selectRows.id) {
    return
  }
  if (record.qytotalRewards) {
    handleDetail(record);
  } else {
    handleEdit(record);
  }
}

function rowClassName(record) {
  return record.id === selectRows.id ? 'row-selected' : '';
}

/**
 * 删除事件
 */
async function handleDelete() {
  if (!selectRows.id) {
    return
  }
  await deleteOne({ id: selectRows.id }, reload);
}

/**
 * 删除事件
 */
async function handleDetail(record: Recordable) {
  if (!selectRows.id) {
    return
  }
  Object.assign(record, selectRows)
  openDetail(true, {
    record,
    isUpdate: true,
    showFooter: true,
  });
}

// 接单员
async function getUserOptions(value) {
  if (!value) {
    return
  }
  userOptions.value = await getUsersByDepartId({ id: value });
}

const cascader = reactive<any>({
  ids: [],
  options: [],
});

function customerCascader(value) {
  if (!value || value.length < 2) {
    queryParam.customerId = "";
  } else {
    queryParam.customerId = value[value.length - 1];
  }
}

const filter = (inputValue: string, path) => {
  return path.some((option) => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
};

onMounted(async () => {
  await nextTick();
  let res = await customerSelect();
  Object.assign(cascader.options, res);
});

</script>
<style scoped>
  span {
    font-weight: 600;
    font-size: 11px;
  }
  span:not(:last-child) {
    margin-right: 12px;
  }
  label {
    margin-left: 5px;
    font-size: 16px;
  }
</style>